  <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<title>群星网约车</title>
<link rel="icon" href="../image/carMR.png" type="image/png">
  <style>
	.order-table {
		padding: 40px;
	}
	.dialog-content {
  display: flex;
  justify-content: space-between;
}

.info-section {
  width: 45%;
}

.info-section h3 {
  margin-bottom: 10px;
}

.info-section p {
  margin: 5px 0;
}
  </style>
</head>
<!--引入相关的文件-->
<script src="../js/vue.js"></script>
<script src="../element-ui/lib/index.js"></script>
<link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
<script src="../js/axios-0.18.0.js"></script>
<body>
<div id="app">
<div class="order-table">
	<span>订单信息：</span>
		<el-input v-model="search" placeholder="订单详情搜索" clearable @clear="handleSearch" @input="handleSearch" style="max-width: 200px;"></el-input>
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	<span>订单状态：</span>
	<el-input v-model="searchOrder" placeholder="订单状态搜索" clearable @clear="handleSearch" @input="handleSearch" style="max-width: 200px;"></el-input>
		<el-table :data="orders" style="width: 100%"  @row-click="handleRowClick">
			<el-table-column prop="orderId" label="订单编号" width="120"></el-table-column>
			<el-table-column prop="driverId" label="司机编号" width="120"></el-table-column>
			<el-table-column prop="userId" label="乘客编号" width="120"></el-table-column>
			<el-table-column prop="departureLocation" label="起点" width="150"></el-table-column>
			<el-table-column prop="destinationLocation" label="终点" width="150"></el-table-column>
			<el-table-column prop="orderDate" label="发起时间" width="200"></el-table-column>
			<el-table-column prop="totalAmount" label="预期金额" width="100"></el-table-column>
			<el-table-column prop="actualAmount" label="实际金额" width="100"></el-table-column>
			<el-table-column prop="status" label="订单状态" width="120">
				<template slot-scope="scope">
					<el-tag
							:type="getOrderStatusType(scope.row.status)"
							@click="confirmUpdateUserRatingsStatus(scope.row)"
					>
						{{ scope.row.status }}
					</el-tag>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalOrders"
				:page-size="pageSize"
				:current-page="currentPage"
				:page-sizes="[5, 10, 20, 50]"
				@current-change="handlePageChange"
				@size-change="handleSizeChange">
		</el-pagination>
		    <el-dialog :visible.sync="dialogVisible" title="人员详情" width="50%">
		      <div class="dialog-content">
		        <div class="info-section">
		          <h3>司机信息</h3>
		          <p><strong>用户名:</strong> {{ driverInfo.username }}</p>
		          <p><strong>手机号:</strong> {{ driverInfo.phoneNumber }}</p>
		          <p><strong>车牌号:</strong> {{ driverInfo.licensePlate }}</p>
		          <p><strong>邮箱:</strong> {{ driverInfo.email }}</p>
		          <p><strong>状态:</strong>
		            <el-tag :type="getDriverStatusType(driverInfo.status)">
		              {{ driverInfo.status }}
		            </el-tag>
		          </p>
		        </div>
		        <div class="info-section">
		          <h3>用户信息</h3>
		          <p><strong>用户名:</strong> {{ userInfo.username }}</p>
		          <p><strong>手机号:</strong> {{ userInfo.phoneNumber }}</p>
		          <p><strong>创建时间:</strong> {{ userInfo.createdAt }}</p>
		          <p><strong>邮箱:</strong> {{ userInfo.email }}</p>
		          <p><strong>状态:</strong>
		            <el-tag :type="getUserStatusType(userInfo.status)">
		              {{ userInfo.status }}
		            </el-tag>
		          </p>
		        </div>
		      </div>
		      <span slot="footer" class="dialog-footer">
		        <el-button @click="dialogVisible = false">关闭</el-button>
		      </span>
		    </el-dialog>
	</div>
</div>


<script>
	// request拦截器，将用户token放入头中
	axios.interceptors.request.use(
			config => {
				let token = localStorage.getItem("token"); // 确保 token 正确存储在 localStorage 中
				if (token) {
					config.headers['token'] = token;
				}
				return config;
			},
			error => {
				console.log(error);
				return Promise.reject(error);
			}
	);
  // 创建一个vue的实例对象,里面写那些数据和方法(一个是页面加载完后自动执行的方法，一个是其他操作后执行的代码)
  // 创建 Vue 实例
  new Vue({
    el: '#app',
    data() {
      return {
		userId: "",
		userName: "",
		avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 默认头像链接
		search: '',
	    searchOrder: '',
		currentPage: 1,
		pageSize: 10,
		totalOrders: 0,
		orders: [
			{ orderId: '123', driverId: '123' ,userId: '456', departureLocation: '北京', destinationLocation: '上海', orderDate: '2023-01-01 12:00:00', totalAmount: 100.5,actualAmount: 100.0, status: '已完成' },
			{ orderId: '124', driverId: '234' ,userId: '457', departureLocation: '广州', destinationLocation: '深圳', orderDate: '2023-01-02 14:30:00', totalAmount: 80.0,actualAmount: 70.0, status: '进行中' },
			// 继续添加订单
		],
		dialogVisible: false,
		driverInfo: {
		  username: '',
		  phoneNumber: '',
		  licensePlate: '',
		  status: '',
		  email: ''
		},
		userInfo: {
			username: '',
			phoneNumber: '',
			email: '',
			createdAt: '',
			status: ''
		},
	  statusMap: {  // 在 data 中定义映射关系
		  '待处理': '1',
		  '已确认': '2',
		  '已完成': '3',
		  '已取消': '4',
		  '待付款': '5'
	  }
      }
    },
    methods: {
	confirmUpdateUserRatingsStatus(order){
		const newStatus = order.status === '待付款' ? '已完成' : '待付款';
		this.$confirm(`确认要将状态修改为${newStatus}吗？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			this.updateUserRatingsStatus(order, newStatus);
		}).catch(() => {
			this.$message.info('取消修改');
		});
	},
	updateUserRatingsStatus(order, newStatus) {
		axios.put(`/order/orders/updateStatusSe`, {
			orderId: order.orderId,
			status: this.statusMap[newStatus]
		}).then(response => {
			if (response.data.code === 1) {
				this.$message.success('状态更新成功');
				order.status = newStatus;
			} else {
				this.$message.error('状态更新失败');
			}
		}).catch(error => {
			console.log(error);
			this.$message.error('状态更新失败');
		});
	},
	fetchOrders() {
		const mappedStatus = this.statusMap[this.searchOrder] || this.searchOrder;
		axios.get(`/order/orders/getOrderByManager`, {
			params: {
				page: this.currentPage,
				size: this.pageSize,
				keyword: this.search,
				keywordOrder: mappedStatus
			}
		}).then(response => {
			if (response.data.code === 1) {
				console.log("成功获取订单信息");
				const orders = response.data.data.list.map(order => {
					// 处理订单状态
					switch (order.status) {
						case '1':
							order.status = '待处理';
							break;
						case '2':
							order.status = '已确认';
							break;
						case '3':
							order.status = '已完成';
							break;
						case '4':
							order.status = '已取消';
							break;
						default:
							order.status = '待付款';
							break;
					}
					// 处理金额
					if (!order.totalAmount) {
						order.totalAmount = '未接单';
					}
					if(!order.actualAmount){
						order.actualAmount='未接单';
					}
					if(!order.driverId){
						order.driverId='未接单';
					}
					// 处理发起时间
					if (order.orderDate) {
						order.orderDate = order.orderDate.replace('T', ' ');
					}
					return order;
				});
				this.orders = orders;
				this.totalOrders = response.data.data.total;
			}
		});
	},
	handleSearch() {
		this.currentPage = 1;
		this.fetchOrders();
	},
	handlePageChange(page) {
		this.currentPage = page;
		this.fetchOrders();
	},
	handleSizeChange(size) {
		this.pageSize = size;
		this.currentPage = 1;
		this.fetchOrders();
	},
	handleRowClick(row) {
		if (row.driverId === '未接单') {
			this.$message.warning('该订单未接取');
			return;
		}
	      this.fetchDriverInfo(row.driverId);
	      this.fetchUserInfo(row.userId);
	      this.dialogVisible = true;
	    },
	fetchDriverInfo(driverId) {
		axios.get('/driver/drivers/getById?driverId=' + driverId)
				.then(response => {
					if (response.data.code === 1) {
						// 处理单个对象
						let order = response.data.data;
						switch (order.status) {
							case '1':
								order.status = '在线';
								break;
							case '2':
								order.status = '接单中';
								break;
							case '3':
								order.status = '离线';
								break;
							case '4':
								order.status = '暂停服务';
								break;
							default:
								order.status = '未知状态'; // 添加默认情况处理
						}
						this.driverInfo = order; // 将单个对象转换为数组
					} else {
						this.$message.error('失败');
					}
				})
				.catch(error => {
					console.log(error);
					this.$message.error('请求失败');
				});
		},
	fetchUserInfo(userId) {
		axios.get('/user/users/getById?userId=' + userId)
				.then(response => {
					if (response.data.code === 1) {
						// 处理单个对象
						let user = response.data.data;
						switch (user.status) {
							case '1':
								user.status = '活跃';
								break;
							case '0':
								user.status = '冻结';
								break;
							default:
								user.status = '未知状态'; // 添加默认情况处理
						}
						this.userInfo = user; // 将单个对象转换为数组
					} else {
						this.$message.error('失败');
					}
				})
				.catch(error => {
					console.log(error);
					this.$message.error('请求失败');
				});
	},
	getOrderStatusType(status) {
		switch (status) {
			case '待处理':
				return 'info';
			case '已确认':
				return 'success';
			case '已完成':
				return 'success';
			case '已取消':
				return 'danger';
			case '待付款':
				return 'warning';
			default:
				return '';
		}
	},
	getDriverStatusType(status) {
		switch (status) {
			case '暂停服务':
				return 'info';
			case '在线':
				return 'success';
			case '离线':
				return 'danger';
			case '接单中':
				return 'warning';
			default:
				return '';
		}
	},
	getUserStatusType(status) {
		switch (status) {
			case '活跃':
				return 'success';
			case '冻结':
				return 'danger';
			default:
				return '';
		}
	},
    },
    mounted(){
		var id=localStorage.getItem('userId');
		this.userId = parseInt(id, 10);
		this.userName = localStorage.getItem('userName');
		this.avatar = localStorage.getItem('pic');
		this.fetchOrders();
    }
  });
</script>
<!-- 不用vue的js代码写在下面-->
<script>
</script>
</body>
</html>